<template>
    <div class="poster-content-box">
        <canvas id="myCanvas" canvas-id="myCanvas" :style="{'width':imageWidth+'px','height':imageHeight+'px'}" ></canvas>
        <button type="primary" open-type="share">分享好友</button>
        <button type="primary" @click="savePicture">保存图片</button>
    </div>
</template>

<script>
export default {
    name: "poster",
    data(){
        return {
            canvasW:0,
            canvasH:0,
            logNum:0,
            saveImageSrc:'',
            imageWidth:0,
            imageHeight:0,
            imageUrl:"../../static/images/poster.jpg"
        }
    },
    onLoad(options){
        this.logNum = options.logNum;
        uni.getImageInfo({
            src:this.imageUrl,
            success:(res)=>{
                this.imageWidth = res.width / 4.5;
                this.imageHeight = res.height / 4.5;
                this.drawImg('myCanvas');
            }
        });
    },
    methods:{
        savePicture(){
            uni.saveImageToPhotosAlbum({
                filePath: this.saveImageSrc,
                success(){
                    uni.showToast({
                        title:"保存成功",
                        icon:"success",
                        duration:1000
                    })
                }
            })
        },
        drawImg(canvasId){
            uni.showToast({
                title:"打卡成功",
                icon:"success",
                duration:1500
            });
            const ctx = uni.createCanvasContext(canvasId);
            ctx.beginPath();
            ctx.fillRect(0,0,this.imageWidth,this.imageHeight);
            ctx.drawImage(this.imageUrl,0,0,this.imageWidth,this.imageHeight);
            ctx.save();
            ctx.stroke();
            ctx.closePath();
            ctx.restore();
            ctx.setTextAlign('left');
            ctx.setFillStyle('#b2b2b2');
            ctx.setFontSize(24);
            ctx.fillText(this.getTime(),0.05*this.imageWidth,0.87*this.imageHeight);
            ctx.setFillStyle('#000000');
            ctx.setFontSize(16);
            ctx.fillText(`已完成${this.logNum / 2}次专注`,0.05 * this.imageWidth,0.95*this.imageHeight);
            ctx.draw();
            setTimeout(()=>{
                const that = this;
                uni.canvasToTempFilePath({
                    canvasId,
                    success(res){
                        that.saveImageSrc = res.tempFilePath;
                    }
                })
            },500);
        },
        getTime(){
            const date = new Date();
            const month = date.getMonth() + 1;
            const day = date.getDate();
            return `${month}月${day}日打卡`;
        }
    },
}
</script>

<style scoped>
@import "poster.css";
</style>